module client.MsgServerClient;

import hunt.logging;
import hunt.util.Serialize;
import config.ConfigurationDefine;
import std.conv : to;
import msgtrans;
import std.algorithm.mutation : SwapStrategy;
import std.algorithm.sorting;
import core.thread;
import message.Constants;
import command.StartAppCommand;

static struct MsgServerNode {
    uint id;
    MessageTransportClient client;
}


class MsgServerClient
{
    private __gshared MsgServerClient _instance;

    private MsgServerNode[] _forwardClientMap;

    private uint _size = 0;

    static public MsgServerClient getInstance()
    {
        if (_instance is null)
        {
            _instance = new MsgServerClient();
        }
        return _instance;
    }

    public void addForwardClient(uint id , MessageTransportClient client)
    {
      synchronized(this)
      {
        _forwardClientMap ~= MsgServerNode(id,client);
        multiSort!("a.id < b.id", SwapStrategy.unstable)(_forwardClientMap);
        _size += 1;
      }
    }

    public uint getSize()
    {
      synchronized(this)
      {
        return _size;
      }
    }

    public MessageTransportClient getForwardClient(string id)
    {
       logInfo("hash:%d",to!int(id) % _size);
       MessageTransportClient client = null;
       synchronized(this)
       {
          client =  _forwardClientMap[to!int(id) % _size].client;
          if (client !is null && client.isClosed)
          {
            logInfo("MessageTransportClient closed!!!!!!");
            while (true)
            {
              client.connect();
              logInfo("isConnected :%s",client.isConnected );
              if(client.isConnected)
              {
                client.send(new MessageBuffer(MESSAGE.CMD_REGISTER_MSGSERVER , []));
                break;
              }
              Thread.sleep(2.seconds);
            }
          }
       }
       return client;
    }
}
